#include "../../../include/online/Configuration.hpp"
#include <stdlib.h>

#include <iostream>
#include <fstream>
#include <sstream>
using std::ifstream;
using std::stringstream;

Configuration *Configuration::_pInstance = Configuration::getInstance(); // 懒汉

Configuration::Configuration(const string &filepath = "../../conf/myconf.conf")
: _filepath(filepath) {
    std::cout << "init Configuration" << std::endl;
    loadConf(); 
}

/**
 *  加载配置文件，并将配置信息存入 _configMap
 */
void Configuration::loadConf() {
    ifstream ifs(_filepath, ifstream::in);
    if (!ifs.good()) {
        std::cout << "Configuration::loadConf: fail to load conf" << std::endl;
    }

    string lines;
    string first, second;
    while (getline(ifs, lines)) {
        stringstream ss(lines);
        ss >> first >> second;
        _configMap[first] = second;
    }
    //打印读取到的配置文件（k-v形式）
    for (auto &item : _configMap) {
        std::cout << item.first << " " << item.second << std::endl;
    }

    std::cout << "load conf successfully" << std::endl;

    ifs.close();
}

Configuration *Configuration::getInstance() {
    if (_pInstance == nullptr) {
        std::cout << "Configuration::getInstance()" << std::endl;
        _pInstance = new Configuration();
        atexit(destroy);
    }

    return _pInstance;
}

void Configuration::destroy() {
    using namespace std;
    cout << "Configuration::destroy()" << endl;

    if (_pInstance) {
        delete _pInstance;
        _pInstance = nullptr;
    }
}

unordered_map<string, string> &Configuration::getConfigMap() {
    return _configMap;
}
